import model from '@backend/model'
import { get_chat_data_list } from './chat'
import { isObject } from 'lodash';
import { BarSubType } from './public/enums'

const PluginKeysAlias: KeyTans = {
    id: 'id',
    is_menu: 'is_menu',
    menu_setting: 'bar',
    plugin_tag: 'tag',
    plugin_name: 'name'
}

// for plugin data return keys
const PluginDataKeys: Array<string> =  ["id", "is_menu", "menu_setting", "plugin_tag", "plugin_name"]

class Plugin{
    private id: number | null = null;
    private record: object | null = null;
    private meta: object | null = null;
    private _pluginData: PluginData | null = null;

    constructor( id: number | NewSimpleParam ){
        if( isObject(id) ){
            this.id = id.id
        }else if( id ){
            this.id = id;
        }
    }

    getId(){
        return this.id
    }

    async getData() : Promise<PluginData>{
        if( !this._pluginData ){
            let re: {[key: string] : any} = null
            const { Plugins: _plugin } = await model('Plugins');
            const d = await _plugin.find({
                select: PluginDataKeys,
                where:{ id: this.id}
            })

            if( d[0]){
                re = re || {}
                for(let key in d[0]){
                    if( PluginKeysAlias[key] ){
                        re[ PluginKeysAlias[key] ] = d[0][key]
                    }else{
                        re[key] = d[0][key]
                    }
                }
            }

            re && (re.bar = JSON.parse(re.bar))
            this._pluginData = re
        }
        return this._pluginData
    }

    async getSubsList(): Promise<ChatData[]>{
        const data = await this.getData()
        const type =  data.bar.type;
        if ( type === BarSubType.CHAT ){
            return await get_chat_data_list()
        }
        return []
    }

    setId( id: number ){
        this.id = id;
    }

    getMeta(){

    }
}

export async function get_plugin( p: number | NewSimpleParam ): Promise<Plugin>{
    return Promise.resolve( new Plugin( p ))
}

export async function get_plugin_subs ( id: number ) {
    const plugin = await get_plugin( id);
    return await plugin.getSubsList()
}

export async function get_plugin_data( where: object ): Promise<Array<PluginData>>{
    const re:Array<PluginData> = []
    const plugins = await get_plugins(where)

    for( const p of plugins){
        re.push( await p.getData() )
    }
    return re;
}

export async function get_plugins( where: object ): Promise< Array<Plugin> > {
    const plugins: Array<Plugin> = []
    const { Plugins: _plugin_dataSource }= await model('Plugins')
    where = Object.assign({order: {
            id: "DESC",
        }}, where)
    const list = await _plugin_dataSource.find( where )
    for(const p of list){
        plugins.push( await get_plugin(p) )
    }
    return plugins
}

export function has_plugin ( idOrName : number | string) : boolean{ 
    let has = false
    return has
}